package com.koron.css2.clientCenter.impl;

import com.koron.css2.ServerInterface;
import com.koron.css2.baseConfig.mapper.BusinessAreaMapper;
import com.koron.css2.clientCenter.bean.*;
import com.koron.css2.clientCenter.mapper.AccountInfoMapper;
import com.koron.css2.clientCenter.mapper.CtmInfoMapper;
import com.koron.css2.clientCenter.mapper.OpenUserMapper;
import com.koron.css2.clientCenter.mapper.UserInfoMapper;
import com.koron.css2.meterService.dto.MsInfoDto;
import com.koron.css2.meterService.mapper.MsInfoMapper;
import com.koron.css2.serviceManage.bean.*;
import com.koron.css2.serviceManage.mapper.UserDiscountMapper;
import com.koron.css2.serviceManage.mapper.UserMixtureMapper;
import com.koron.css2.serviceManage.utils.JsonUtils;
import com.koron.css2.serviceManage.vo.UserDiscountVO;
import com.koron.css2.serviceManage.vo.UserMixtureVO;
import com.koron.util.Constant;
import com.koron.util.DBSourceUtils;
import com.koron.util.Tools;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.swan.bean.MessageBean;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

public class OpenUserAdd implements ServerInterface {

    @Override
    //@ValidationKey(clazz = OpenUserBean.class,method = "insert")
    public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {
        @SuppressWarnings("rawtypes")
        MessageBean<Map> msg = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "保存成功", Map.class);

        OpenUserBean bean = JsonUtils.jsonToPojoIgnoreNone(JsonUtils.objectToJson(req.getData()), OpenUserBean.class);

        UserOpenBean userOpenBean = bean.getUserOpenInfo();//为了获取附件临时ID
        UserOpenBean userOpen = new UserOpenBean();
        try {
            OpenUserMapper mapper = factory.getMapper(OpenUserMapper.class);
            UserInfoMapper userMapper = factory.getMapper(UserInfoMapper.class);
            AccountInfoMapper accountMapper = factory.getMapper(AccountInfoMapper.class);
            CtmInfoMapper ctmMapper = factory.getMapper(CtmInfoMapper.class);
            String openId = "";
            AccountInfoBean accountInfo = bean.getAccountInfo();
            CtmInfoBean ctmInfo = bean.getCtmInfo();
            UserBean user = bean.getUserInfo();
            //获取配置参数，是否取营业区域默认册本号
            BusinessAreaMapper businessAreaMapper = factory.getMapper(BusinessAreaMapper.class);
            String dbEnv = DBSourceUtils.getDbEnv(userInfo.getCurWaterCode());
            String on_off = Tools.getConfigValue(dbEnv, "DEFAULT_BOOK_NO_ON_OFF");
            if ("1".equals(on_off)) {
                BusinessAreaBean business = businessAreaMapper.findBusinessAreaInfoById(user.getBusinessArea());
                user.setBookNo(business.getBookNo());
            }
            if ("1".equals(ctmInfo.getCertType())) {
                if (!checkIdentityCode(ctmInfo.getCertNo())) {
                    return MessageBean.create(Constant.ILLEGAL_PARAMETER, "无效的身份证号码", void.class);
                }
                ;
            }
            /*** 粤海版本没有结构化地址 如果需要结构化地址可参考银川版本 ***/
            /*PubAdminAreaMapper pmapper = factory.getMapper(PubAdminAreaMapper.class, "_default");
            String clientContractAddr = pmapper.selectFullNameById(user.getClientContractAddr());
            String clientAddr = pmapper.selectFullNameById(ctmInfo.getClientAddr());
            if (StringUtils.isEmpty(clientContractAddr)) {
                user.setClientContractAddr(null);
            }
            if (StringUtils.isEmpty(clientAddr)) {
                ctmInfo.setClientAddr(null);
            }*/
            user.setSetupMeterAddr(user.getClientContractAddrDetail());
            ctmInfo.setCtmAddr(ctmInfo.getClientAddrDetail());

            if (StringUtils.isEmpty(user.getMeterNo())) {
                return MessageBean.create(Constant.ILLEGAL_PARAMETER, "水表编号不能为空", void.class);
            }
            String userNo = Tools.getBillNo(factory, "USER_INFO", userInfo.getCurWaterCode());
            // 获取账户信息
            if (StringUtils.isEmpty(accountInfo.getAccountNo()) || "新开户".equals(accountInfo.getAccountNo())) {
                accountInfo.setAccountNo(Tools.getSameAccountNo(userNo));
            }
            accountInfo.setCreateInfo(userInfo);
            // 获取客户信息
            if (StringUtils.isEmpty(ctmInfo.getCtmNo())) {
                ctmInfo.setCtmNo(Tools.getSameCtmNo(userNo));
            }
            ctmInfo.setCreateInfo(userInfo);
            // 获取用户信息
            user.setUserNo(userNo);
            user.setCreateInfo(userInfo);
            user.setCtmNo(ctmInfo.getCtmNo());
            user.setStatus("1");
            user.setLockFlag(0);
            // user.setOpenDate(Tools.getCurrentDate());
            user.setAccountNo(accountInfo.getAccountNo());
            ctmInfoToUserInfo(ctmInfo, user);
			/*
			userOpen.setCreateInfo(userInfo);
			userOpen.setUserAccountTempId(accountInfo.getId());
			userOpen.setUserCtmTempId(ctmInfo.getId());
			userOpen.setUserInfoTempId(user.getId());
			userOpen.setBillNo(Tools.getBillNo(factory, "USER_OPEN"));
			userOpen.setBillDate(Tools.getCurrentDate());
			mapper.userOpenAdd(userOpen);//保存到单据上
			*/
            userOpen.setCreateInfo(userInfo);
            userOpen.setUserAccountTempId(accountInfo.getId());
            userOpen.setUserCtmTempId(ctmInfo.getId());
            userOpen.setUserInfoTempId(user.getId());
            userOpen.setUserOpenId(openId);
            mapper.userOpenTempAdd(userOpen);
            openId = userOpen.getId();
            // 添加用水类型名称
            String useWaterTypeName = getUseWaterTypeName(user.getUseWaterType(), bean.getUserMixtureData(), userMapper);
            user.setUseWaterTypeName(useWaterTypeName);
            //获取水表数据
            MsInfoMapper msmapper = factory.getMapper(MsInfoMapper.class);
            MsInfoDto meter = msmapper.getMsInfoByNo(user.getMeterNo());
            user.setMeterType(meter.getMeterType());
            // 保存开户信息
            accountMapper.accountInfoAdd(accountInfo, AccountInfoBean.ACCOUNTTEMP);
            ctmMapper.ctmInfoAdd(ctmInfo, CtmInfoBean.CTMTEMP);
            userMapper.userInfoAdd(user, UserBean.USERTEMP);

            //修改混合用水
            if (bean.getUserMixtureData() != null) {
                UserMixtureMapper userMixtureMapper = factory.getMapper(UserMixtureMapper.class);
                UserMixtureVO vo = bean.getUserMixtureData();
                for (UserMixtureBean userMixtureBean : vo.getList()) {
                    userMixtureBean.setCreateInfo(userInfo);
                    userMixtureBean.setTenantId(openId);
                    userMixtureBean.setUserNo(user.getUserNo());
                    userMixtureBean.setWaterRatio(userMixtureBean.getWaterRatio().replace("%", ""));
                    userMixtureMapper.insertTemp(userMixtureBean);
                }
            }

            //修改费用折扣
            if (bean.getDiscountData() != null) {
                UserDiscountMapper userDiscountMapper = factory.getMapper(UserDiscountMapper.class);
                UserDiscountVO vo = bean.getDiscountData();
                for (UserDiscountBean userDiscountBean : vo.getList()) {
                    userDiscountBean.setCreateInfo(userInfo);
                    userDiscountBean.setTenantId(openId);
                    userDiscountBean.setUserNo(user.getUserNo());
                    userDiscountMapper.insertTemp(userDiscountBean);
                }
            }

            //返回ID
            // 获取营业区域
            if (!StringUtils.isEmpty(user.getBusinessArea())) {
                user.setBusinessAreaName(
                        businessAreaMapper.findBusinessAreaById(user.getBusinessArea(), userInfo.getCurWaterCode()));
            }
            //返回水表IMST

            Map<String, String> map = new HashMap<String, String>();
            map.put("id", openId);
            map.put("ctmNo", ctmInfo.getCtmNo());
            map.put("accountNo", user.getAccountNo());
            map.put("userNo", user.getUserNo());
            map.put("ctmName", ctmInfo.getCtmName());
            map.put("bookNo", user.getBookNo());
            map.put("businessAreaName", user.getBusinessAreaName());
            map.put("setupMeterAddr", user.getSetupMeterAddr());
            map.put("setupMeterDate", user.getSetupMeterDate());
            map.put("useWaterTypeName", user.getUseWaterTypeName());
            map.put("imei", meter.getImei());
            map.put("imsi", meter.getImsi());
            msg.setData(map);
//			BaseReceiptAccessoryMapper accessoryMapper = factory.getMapper(BaseReceiptAccessoryMapper.class);
//			if(!StringUtils.isBlank(userOpenBean.getTempId()))		//修改附件ID
//				accessoryMapper.updateAccessoryReceiptId(openId, userOpenBean.getTempId());
            //输出执行结果
            return msg;
        } catch (Exception e) {
            logger.error("开户失败", e);
            return MessageBean.create(Constant.MESSAGE_INT_FAIL, "开户失败", void.class);
        }
    }

    public static boolean checkIdentityCode(String identityCode) {
        // 校验身份证位数为18位
        if (!identityCode.matches("\\d{17}(\\d|x|X)$")) {
            return false;
        }
        Date d = new Date();
        DateFormat df = new SimpleDateFormat("yyyyMMdd");
        int year = Integer.parseInt(df.format(d));
        if (Integer.parseInt(identityCode.substring(6, 10)) < 1900
                || Integer.parseInt(identityCode.substring(6, 10)) > year) {// 7-10位是出生年份，范围应该在1900-当前年份之间
            return false;
        }
        if (Integer.parseInt(identityCode.substring(10, 12)) < 1
                || Integer.parseInt(identityCode.substring(10, 12)) > 12) {// 11-12位代表出生月份，范围应该在01-12之间
            return false;
        }
        if (Integer.parseInt(identityCode.substring(12, 14)) < 1
                || Integer.parseInt(identityCode.substring(12, 14)) > 31) {// 13-14位是出生日期，范围应该在01-31之间
            return false;
        }
        // 校验第18位
        // S = Sum(Ai * Wi), i = 0, ... , 16 ，先对前17位数字的权求和
        // Ai:表示第i位置上的身份证号码数字值
        // Wi:表示第i位置上的加权因子
        // Wi: 7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2
        String[] tempA = identityCode.split("|");
        int[] a = new int[17];
        for (int i = 0; i < tempA.length - 1; i++) {
            a[i] = Integer.parseInt(tempA[i]);
        }
        int[] w = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2}; // 加权因子
        int sum = 0;
        for (int i = 0; i < 17; i++) {
            sum = sum + a[i] * w[i];
        }
        // Y = mod(S, 11)
        // 通过模得到对应的校验码
        // Y: 0 1 2 3 4 5 6 7 8 9 10
        // 校验码: 1 0 X 9 8 7 6 5 4 3 2
        String[] v = {"1", "0", "x", "9", "8", "7", "6", "5", "4", "3", "2"}; // 校验码
        int y = sum % 11;
        if (!v[y].equalsIgnoreCase(identityCode.substring(17))) {// 第18位校验码错误
            return false;
        }
        return true;
    }

    /**
     * 用于冗余字段的整理
     *
     * @param ctmBean
     * @param userBean
     */
    public static void ctmInfoToUserInfo(CtmInfoBean ctmBean, UserBean userBean) {
        userBean.setCtmName(ctmBean.getCtmName());
        userBean.setCertNo(ctmBean.getCertNo());
        userBean.setCertType(ctmBean.getCertType());
        userBean.setLinkTel(ctmBean.getLinkTel());
        userBean.setMobile(ctmBean.getMobile());
        userBean.setFaxNumber(ctmBean.getFaxNumber());
        userBean.setCtmAddr(ctmBean.getCtmAddr());
    }

    public static String getUseWaterTypeName(String useWaterType, UserMixtureVO vo, UserInfoMapper userMapper) {
        if (vo != null)
            return getUseWaterTypeName(useWaterType, vo.getList(), userMapper);
        return getUseWaterTypeName(useWaterType, new ArrayList<>(), userMapper);
    }

    public static String getUseWaterTypeName(String useWaterType, List<UserMixtureBean> list, UserInfoMapper userMapper) {
        String useWaterTypeName = "";
        if (list != null && list.size() > 0) {
            for (UserMixtureBean m : list) {
                String u = userMapper.selectUseWaterTypeName(m.getUseWaterType());
                if (m.getResidue() == 0) {
                    useWaterTypeName = Tools.subZeroAndDot(m.getWaterRatio()).replace("%", "").replace(".00", "") + "%" + u + ";" + useWaterTypeName;
                } else {
                    useWaterTypeName = useWaterTypeName + Tools.subZeroAndDot(m.getWaterRatio()).replace("%", "").replace(".00", "") + "%" + u + ";";
                }
            }
        } else {
            useWaterTypeName = userMapper.selectUseWaterTypeName(useWaterType);
        }
        return useWaterTypeName;
    }
}
